package com.project.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.project.model.CityModel;
import com.project.model.CommentModel;
import com.project.model.EventModel;
import com.project.model.FavoritesModel;
import com.project.model.IndustryModel;
import com.project.model.IndustrySmallModel;
import com.project.model.ObtainRedPacketMemberModel;
import com.project.model.ShopModel;
import com.project.model.StreetModel;
import com.project.service.CityService;
import com.project.service.CommentService;
import com.project.service.EventService;
import com.project.service.FavoritesService;
import com.project.service.IndustryService;
import com.project.service.IndustrySmallService;
import com.project.service.MemberService;
import com.project.service.RedPacketService;
import com.project.service.ShopService;
import com.project.service.StreetService;
import com.project.utils.DistanceUtil;

@Controller
@RequestMapping(value = "/shop")
public class ShopController {
	private static Logger logger = LoggerFactory.getLogger(ShopController.class);
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private RedPacketService redPacketService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private IndustryService industryService;
	
	@Autowired
	private IndustrySmallService industrySmallService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private StreetService streetService;
	
	@Autowired
	private EventService eventService;
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private FavoritesService favoritesService;
	
	@RequestMapping("")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		String location = "";
		String viewName = "my_location.jsp";
		
		String area = "";
		String street = "";
		String keyword = "";
		int industry = 0;
		int industry_small = 0;
		if (null != request.getParameter("area") && !"".equals(request.getParameter("area").trim())) {
			area = request.getParameter("area");
		}
		if (null != request.getParameter("street") && !"".equals(request.getParameter("street").trim())) {
			street = request.getParameter("street");
		}
		if (null != request.getParameter("t") && !"".equals(request.getParameter("t").trim())) {
			try {
				industry = Integer.parseInt(request.getParameter("t").toString());
				view.addObject("name", request.getParameter("name").toString());
			} catch (Exception e) {
				industry = 0;
			}
		}
		if (null != request.getParameter("t2") && !"".equals(request.getParameter("t2").trim())) {
			try {
				industry_small = Integer.parseInt(request.getParameter("t2").toString());
				view.addObject("name", request.getParameter("name").toString());
			} catch (Exception e) {
				industry_small = 0;
			}
		}
		if (null != request.getParameter("keyword") && !"".equals(request.getParameter("keyword").trim())) {
			keyword = request.getParameter("keyword");
		}
		view.addObject("keyword", keyword);
		
		if (null != request.getParameter("city") && !"".equals(request.getParameter("city").trim())) {
			location = request.getParameter("city");
		} else if (null != request.getSession().getAttribute("location") && !"".equals(request.getSession().getAttribute("location"))) {
			location = request.getSession().getAttribute("location").toString();
		}
		if (null != location && !"".equals(location)) {
			view.addObject("location", location);
			viewName = "shop_list.jsp";
			
			String lng = "116.331398";
			String lat = "39.897445";
			if (null != request.getSession().getAttribute("lng") && !"".equals(request.getSession().getAttribute("lng"))) {
				lng = request.getSession().getAttribute("lng").toString();
			}
			if (null != request.getSession().getAttribute("lat") && !"".equals(request.getSession().getAttribute("lat"))) {
				lat = request.getSession().getAttribute("lat").toString();
			}
			
			// 根据城市名称获取城市CODE
			List<CityModel> citys = cityService.getCityCodeByName(location);
			List<CityModel> areas = new ArrayList<CityModel>();
			if (null != citys && citys.size() > 0) {
				// 根据城市CODE获取所有下级县、区
				areas = cityService.getCityModelByParentCode(citys.get(0).getCode());
			}
			view.addObject("areas", areas);
			
			List<StreetModel> streets = new ArrayList<StreetModel>();
			if (null != citys && citys.size() > 0) {
				// 根据市CODE获取所有街道信息
				streets = streetService.getStreetByCityCode(citys.get(0).getCode());
			}
			view.addObject("streets", streets);
			
			String city = "";
			if (null != citys && citys.size() > 0) {
				city = citys.get(0).getCode();
			}
			List<ShopModel> condition_shopModels = getShopList(city, area, street, industry, industry_small, lat, lng, 1, keyword);
			view.addObject("shops", condition_shopModels);
			
			// 获取所有一级分类
			List<IndustryModel> industrys =  industryService.getIndustryModelAll(city);
			view.addObject("industrys", industrys);
			
			// 获取所有二级分类
			List<IndustrySmallModel> industrySmalls = industrySmallService.getIndustrySmallModelAll(city);
			view.addObject("industrySmalls", industrySmalls);
		}
		view.setViewName(viewName);
		return view;
	}
	
	@RequestMapping("/search")
	public @ResponseBody Map<String, Object> search(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String city = "";
		String area = "";
		String street = "";
		String keyword = "";
		int industry = 0;
		int industry_small = 0;
		int sort = 1;
		String lng = "116.331398";
		String lat = "39.897445";
		if (null != request.getSession().getAttribute("lng") && !"".equals(request.getSession().getAttribute("lng"))) {
			lng = request.getSession().getAttribute("lng").toString();
		}
		if (null != request.getSession().getAttribute("lat") && !"".equals(request.getSession().getAttribute("lat"))) {
			lat = request.getSession().getAttribute("lat").toString();
		}
		if (null != request.getParameter("city") && !"".equals(request.getParameter("city").trim())) {
			city = request.getParameter("city").toString().trim();
			List<CityModel> citys = cityService.getCityCodeByName(city);
			if (null != citys && citys.size() > 0) {
				city = citys.get(0).getCode();
			}
		}
		if (null != request.getParameter("area") && !"".equals(request.getParameter("area").trim())) {
			area = request.getParameter("area").toString().trim();
		}
		if (null != request.getParameter("street") && !"".equals(request.getParameter("street").trim())) {
			street = request.getParameter("street").toString().trim();
		}
		if (null != request.getParameter("keyword") && !"".equals(request.getParameter("keyword").trim())) {
			keyword = request.getParameter("keyword").toString().trim();
		}
		try {
			industry = Integer.parseInt(request.getParameter("industry").toString().trim());
		} catch (Exception e) {
			// TODO: handle exception
			industry = 0;
		}
		try {
			industry_small = Integer.parseInt(request.getParameter("industry_small").toString().trim());
		} catch (Exception e) {
			// TODO: handle exception
			industry_small = 0;
		}
		try {
			sort = Integer.parseInt(request.getParameter("sort").toString().trim());
		} catch (Exception e) {
			// TODO: handle exception
			sort = 1;
		}
		List<ShopModel> condition_shopModels = getShopList(city, area, street, industry, industry_small, lat, lng, sort, keyword);
		map.put("shops", condition_shopModels);
		return map;
	}
	
	@RequestMapping("{id}")
	public ModelAndView info(@PathVariable("id") int id, HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		
		String lng = "116.331398";
		String lat = "39.897445";
		
		if (null != request.getSession().getAttribute("lng") && !"".equals(request.getSession().getAttribute("lng"))) {
			lng = request.getSession().getAttribute("lng").toString();
		}
		if (null != request.getSession().getAttribute("lat") && !"".equals(request.getSession().getAttribute("lat"))) {
			lat = request.getSession().getAttribute("lat").toString();
		}
		
		ShopModel shopModel = shopService.getById(id);
		
		String distance_str = DistanceUtil.getDistance(lat, lng, shopModel.getLatitude(), shopModel.getLongitude());
		int distance = Integer.parseInt(distance_str);
		if (distance > 1000) {
			 java.text.DecimalFormat df = new java.text.DecimalFormat("#");
			distance_str = df.format(distance/1000) + "km";
		} else {
			distance_str = distance_str+"m";
		}
		shopModel.setDistance(distance_str);
		
		List<EventModel> eventModels = eventService.getListByShopId(shopModel.getId());
		if (null != eventModels && eventModels.size() > 0) {
			view.addObject("event", eventModels.get(0));
			
			List<ObtainRedPacketMemberModel> obtainRedPacketMember = memberService.getObtainRedPacketMemberModelByPhone(eventModels.get(0).getId());
			if (null == obtainRedPacketMember || obtainRedPacketMember.size() == 0 || null == obtainRedPacketMember.get(0)) {
				obtainRedPacketMember = new ArrayList<ObtainRedPacketMemberModel>();
			}
			view.addObject("obtainRedPacketMembers", obtainRedPacketMember);
			
			int redPacketCount = redPacketService.getRedPacketCountByEventId(eventModels.get(0).getId());
			view.addObject("redPacketCount", redPacketCount);
		}
		List<CommentModel> comments = commentService.getListByShopId(shopModel.getId());
		if (null == comments || comments.size() == 0 || null == comments.get(0)) {
			comments = new ArrayList<CommentModel>();
		}
		double total_star = 0;
		for (int i = 0; i < comments.size(); i++) {
			total_star += comments.get(i).getTotalStar().doubleValue();
		}
		if (comments.size() > 0) {
			total_star = total_star/comments.size();
		}
		view.addObject("comments", comments);
		view.addObject("shop", shopModel);
		java.text.DecimalFormat df = new java.text.DecimalFormat("#.0");  
		view.addObject("total_star", df.format(total_star));
		view.setViewName("../shop.jsp");
		return view;
	}
	
	@RequestMapping("quota")
	public ModelAndView quota(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		String viewName = "/again_login.jsp";
		if (null != request.getSession().getAttribute("userId")) {
			int user_id = (int)request.getSession().getAttribute("userId");
			Map<String, Integer> map = new HashMap<String, Integer>();
			map.put("user_id", user_id);
			List<EventModel> eventModels = eventService.getEventQuota(map);
			if (null != eventModels && eventModels.size() > 0) {
				view.addObject("event", eventModels.get(0));
				viewName = "/quota.jsp";
			} else {
				viewName = "/error.jsp";
			}
		} else {
			view.addObject("page", "/shop/quota");
		}
		view.setViewName(viewName);
		return view;
	}
	
	@RequestMapping("/add_favorites")
	public @ResponseBody Map<String, Object> add_favorites(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		int userId = (int)session.getAttribute("userId");
		int shop_id = 0;
		try {
			shop_id = Integer.parseInt(request.getParameter("shop_id"));
			FavoritesModel favoritesModel = new FavoritesModel();
			favoritesModel.setMember_id(userId);
			favoritesModel.setShop_id(shop_id);
			List<FavoritesModel> favoritesModels = favoritesService.listFavoritesModelByUserId(userId);
			boolean flag = false;
			for (int i=0;i<favoritesModels.size(); i++) {
				if (favoritesModels.get(i).getShop_id() == shop_id) {
					flag = true;
				}
			}
			if (flag == false) {
				if (favoritesService.insert(favoritesModel) > 0) {
					map.put("code", "1");
					map.put("msg", "收藏成功");
				} else {
					map.put("code", "0");
					map.put("msg", "收藏失败");
				}
			} else {
				map.put("code", "0");
				map.put("msg", "您已收藏过该店铺");
			}
		} catch (Exception e){
			map.put("code", "0");
			map.put("msg", "收藏失败");
		}
		return map;
	}
	
	@RequestMapping("favorites")
	public ModelAndView favorites(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		String viewName = "/again_login.jsp";
		if (null != session.getAttribute("userId")) {
			int userId = (int)session.getAttribute("userId");
			List<ShopModel> condition_shopModels = shopService.getShopModelByFavoritesUser(userId);
			
			if (null != condition_shopModels) {
				String lng = "116.331398";
				String lat = "39.897445";
				if (null != request.getSession().getAttribute("lng") && !"".equals(request.getSession().getAttribute("lng"))) {
					lng = request.getSession().getAttribute("lng").toString();
				}
				if (null != request.getSession().getAttribute("lat") && !"".equals(request.getSession().getAttribute("lat"))) {
					lat = request.getSession().getAttribute("lat").toString();
				}
				for (int i=0; i<condition_shopModels.size(); i++) {
					String distance_str = DistanceUtil.getDistance(lat, lng, condition_shopModels.get(i).getLatitude(), condition_shopModels.get(i).getLongitude());
					int distance = Integer.parseInt(distance_str);
					if (distance > 1000) {
						 java.text.DecimalFormat df = new java.text.DecimalFormat("#");
						distance_str = df.format(distance/1000) + "km";
					} else {
						distance_str = distance_str+"m";
					}
					condition_shopModels.get(i).setDistance(distance_str);
				}
			} else {
				condition_shopModels = new ArrayList<ShopModel>();
			}
			mav.addObject("shops", condition_shopModels);
			viewName = "../favorites.jsp";
		} else {
			mav.addObject("page", "/member/index");
		}
		mav.setViewName(viewName);
		return mav;
	}
	
	private List<ShopModel> getShopList(String city, String area, String street, int industry, int industry_small, String lat, String lng, int sort, String keyword) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("size", 30);
		if (null != city && !"".equals(city)) {
			condition.put("city", city);
		}
		if (null != area && !"".equals(area)) {
			condition.put("area", area);
		}
		if (null != street && !"".equals(street)) {
			condition.put("street", street);
		}
		if (industry > 0) {
			condition.put("p_industry", industry);
		}
		if (industry_small > 0) {
			condition.put("industry", industry_small);
		}
		// 获取店铺列表
		List<ShopModel> condition_shopModels = shopService.getShopModelByCondition(condition);
		if (null != condition_shopModels && condition_shopModels.size() > 0) {
			for (int i=0; i<condition_shopModels.size(); i++) {
				String distance_str = DistanceUtil.getDistance(lat, lng, condition_shopModels.get(i).getLatitude(), condition_shopModels.get(i).getLongitude());
				int distance = Integer.parseInt(distance_str);
				if (distance > 1000) {
					 java.text.DecimalFormat df = new java.text.DecimalFormat("#");
					distance_str = df.format(distance/1000) + "km";
				} else {
					distance_str = distance_str+"m";
				}
				condition_shopModels.get(i).setDistance(distance_str);
			}
			if (sort == 2) {
				// 按点击数倒序  
		        Collections.sort(condition_shopModels, new Comparator<ShopModel>() {
		            public int compare(ShopModel arg0, ShopModel arg1) {
		                double hits0 = Double.parseDouble(arg0.getDistance().replace("km", "").replace("m", ""));
		                double hits1 = Double.parseDouble(arg1.getDistance().replace("km", "").replace("m", ""));
		                if (hits1 > hits0) {
		                    return 1;
		                } else if (hits1 == hits0) {
		                    return 0;
		                } else {
		                    return -1;
		                }
		            }
		        });
			} else if (sort == 3) {
				
			} else if (sort == 4) {
				Collections.sort(condition_shopModels, new Comparator<ShopModel>() {
		            public int compare(ShopModel arg0, ShopModel arg1) {
		                Date hits0 = arg0.getCreateTime();
		                Date hits1 = arg1.getCreateTime();
		                if (hits1.before(hits0)) {
		                    return 1;
		                } else if (hits1 == hits0) {
		                    return 0;
		                } else {
		                    return -1;
		                }
		            }
		        });
			}
		} else {
			condition_shopModels = new ArrayList<ShopModel>();
		}
		
		return condition_shopModels;
	}
}